<?php
/**
 * Created by PhpStorm.
 * User: song
 * Date: 2018/9/11
 * Time: 下午2:29
 */


if (!defined("__APP__")) {
    echo "__APP__常量未定义";
    return false;
}
define('__ROOT__', $_SERVER['DOCUMENT_ROOT'] ?? __DIR__);
define('__TMP__', __APP__ . "/tmp");
define('QingPHP_PATH', dirname(__FILE__));


date_default_timezone_set('PRC'); //设置中国时区

//判断项目是否需要初始化
require_once QingPHP_PATH . "/Init/index.php";
require_once QingPHP_PATH . "/Common/common.php";


function init($request = [], $argv = [])
{
    if (!empty($request)) {
        $_GET = is_array($request->get) ? $request->get : [];
        $_POST = is_array($request->post) ? $request->post : [];
        $_SERVER['HTTP_RAW_POST_DATA'] = $request->rawContent();
    }

    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        unset($argv[0]);
        $arr = array_values($argv);
        $action = isset($arr[0]) ? ucfirst(addslashes($arr[0])) : 'Index';
        $method = isset($arr[1]) ? addslashes($arr[1]) : 'index';
    } else {
        //路由规则
        $arr = array_values(array_filter(explode('/', $_GET['s'] ?? '')));

        $action = isset($arr[0]) ? ucfirst(addslashes($arr[0])) : 'Index';
        $method = isset($arr[1]) ? addslashes($arr[1]) : 'index';
    }

    $_SERVER['APP_ACTION'] = $action;
    $_SERVER['APP_METHOD'] = $method;


    //记录请求日志
    $type = $_SERVER['REQUEST_METHOD'] ?? 'cli';
    if ($type !== 'GET') {
        addLog(["收到{$type}请求]", var_export($_GET, true), getClientIp()]);
    }

    //加载对应控制器
    require_once __APP__ . "/action/BaseAction.php";
    require_once __APP__ . "/action/{$action}Action.php";
    //实例化
    $actionFull = "\app\action\\{$action}Action";
    $actionApi = new $actionFull;

//    ob_start(); //打开缓冲区
    $result = $actionApi->$method();
//    ob_end_clean();


    return $result;
}

function startSwoole($config = [])
{
    //设置默认配置
    $defaultConfig = [
        'reactor_num' => function_exists('\swoole_cpu_num') ? \swoole_cpu_num() * 2 : 4,
//        'worker_num'         => function_exists('\swoole_cpu_num') ? \swoole_cpu_num() * 2 : 40,
        'worker_num' => 100,
        'buffer_output_size' => 1 * 1024 * 1024,
        'socket_buffer_size' => 4 * 1024 * 1024,
        'package_max_length' => 1 * 1024 * 1024,
        'reload_async' => true,
        'max_wait_time' => 15,
        'enable_reuse_port' => true,
        'open_tcp_nodelay' => true,
        'dispatch_mode' => 3,
        'open_tcp_keepalive' => 1,
        'tcp_keepidle' => 1,
        'tcp_keepcount' => 1,
        'tcp_keepinterval' => 1,
        'max_request' => 1000,
    ];
    $config = empty($config) ? $defaultConfig : $config;

    //启动swoole
    $http = new swoole_http_server("0.0.0.0", 9501);
    $http->set($config);


    $http->on("start", function ($server) {
        echo "Swoole http server is started at http://127.0.0.1:9501\n";
    });

    $http->on("request", function ($request, $response) {
        $response->header("Content-Type", "text/plain");

        try {
            $result = init($request);
        } catch (Exception $e) {
            $result = $e->getMessage();
            $response->status($e->getCode());
            echo PHP_EOL . $result . PHP_EOL;
            echo $e->getTraceAsString() . PHP_EOL;
        }
        $result = is_array($result) ? json_encode($result, true) : $result;

        $response->header("Connection", "close");
        $response->end($result);
    });

    $http->start();
}


function SwooleTaskStart()
{
    $serv = new Swoole\Server("127.0.0.1", 9502, SWOOLE_BASE);

    $serv->set(array(
        'worker_num' => 20,
        'task_worker_num' => 100,
    ));

    $serv->on('Receive', function (Swoole\Server $serv, $fd, $from_id, $data) {
        $data = trim($data);
        $task_id = $serv->task($data, 0);
        $serv->send($fd, "分发任务，任务id为$task_id\n");
    });

    $serv->on('Task', function (Swoole\Server $serv, $task_id, $from_id, $data) {
        $data = json_decode(explode("\n", $data)[6], true);

        //任务要执行的代码
        $serv->finish($data);
    });

    $serv->on('Finish', function (Swoole\Server $serv, $task_id, $data) {
        echo "任务完成:" . json_encode($data) . PHP_EOL;
    });

    $serv->on('workerStart', function ($serv, $worker_id) {
        global $argv;
        if ($worker_id >= $serv->setting['worker_num']) {
            swoole_set_process_name("php {$argv[0]}: task_worker");
        } else {
            swoole_set_process_name("php {$argv[0]}: worker");
        }
    });

    $serv->start();

}